<template>
    <div>
        <panle title='临时素材库管理' content="上传临时素材库列表"></panle>
        <div class="searchbar">
            <el-row class="pt20">
                <el-col :span="12">
                    <el-form :inline="true" :model="formInline" class="demo-form-inline">
                        <el-form-item label="">
                            <el-input v-model="formInline.keyword" size="mini" placeholder="搜索文件名称"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-select v-model="formInline.type" size="mini" placeholder="筛选文件类型">
                                <el-option label="图片" value="image"></el-option>
                                <el-option label="视频" value="video"></el-option>
                                <el-option label="文件" value="file"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" size="mini" @click="getSearch">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <div class="searchbar">
                <el-row class="pt20">
                    <el-col :span="12">
                        <!--<PersButton icon="el-icon-edit" size="mini" perms="scrm:files:upload" type="primary" label="上传素材" @click="showMaterial"></PersButton>-->
                        <el-upload class="upload-demo" :action="actions" multiple :on-success="uploadSuccess" ref="upload"
                                   :show-file-list="false" :headers="uploadHeader" :data="uploadData" :on-error="uploadError">
                            <PersButton icon="el-icon-edit" size="mini" perms="scrm:files:upload" type="primary" label="上传图片"></PersButton>
                        </el-upload>
                        <el-button size="mini" @click="init()">刷新</el-button>
                        <!--<pers-button type="danger" size="mini" icon="el-icon-delete" @click="delAll()" perms="files:del" label="批量删除"></pers-button>-->
                    </el-col>
                    <el-col :span="12" style="text-align: right;">
                        <el-button type="primary" size="mini" @click="syncAllFile">更新</el-button>
                    </el-col>
                </el-row>
            </div>
        </div>

        <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all v-loading="loading" @selection-change="handleSelectionChange">
            <!--<el-table-column type="selection" width="55"></el-table-column>-->
            <el-table-column prop="id" label="ID" width="55"></el-table-column>
            <el-table-column prop="http_urls" label="缩略图">
                <template slot-scope="scope">
                    <el-image style="width: 50px; height: 50px" :src="scope.row.src"
                        :preview-src-list="[scope.row.src]" v-if="scope.row.type == 'image'">
                    </el-image>
                    <el-tag type="danger" :label="scope.row.type" effect="plain" size="small"
                        v-if="scope.row.type == 'file'">{{ scope.row.type }}</el-tag>
                    <el-tag type="success" :label="scope.row.type" effect="plain" size="small"
                        v-if="scope.row.type == 'video'">{{ scope.row.type }}</el-tag>


                </template>

            </el-table-column>
            <el-table-column prop="name" label="文件名称"></el-table-column>
            <el-table-column prop="src" label="图片地址"></el-table-column>
            <el-table-column prop="media_id" label="素材ID"></el-table-column>
            <!--<el-table-column prop="creat_by" label="上传者"></el-table-column>-->
            <el-table-column prop="expire_time" label="到期时间">
                <template slot-scope="scope" v-if="scope.row.expire_time > 0">
                    {{new Date(scope.row.expire_time*1000).toLocaleString()}}
                </template>
            </el-table-column>
            <el-table-column prop="fid" label="操作">
                <template slot-scope="scope">
                    <PersButton v-if="scope.row.type != 'image'" type="text" size="mini" icon="el-icon-refresh-left" perms="sys:role:del" label="更新" @click="updateRole(scope.row)"></PersButton>
                    <!--<PersButton type="text" size="mini" icon="el-icon-delete" perms="sys:role:del" label="删除" @click="delRole(scope.row)"></PersButton>-->
                    <!--<PersButton type="text" size="mini" label="复制链接" icon="fa  fa-pencil" perms="node:edit" @click="copy(scope.row)"></PersButton>-->
                </template>
            </el-table-column>
        </el-table>

        <div class="block">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="pageNumber" :page-sizes="[10, 50, 100, 200]" :page-size="pageSize" background
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <SelectMaterial :show="IsShowMaterial" @update="hideMaterial" :selectType="1" @selectSure="selectFile" @tabSet="setTabType" :fileType="0"></SelectMaterial>
    </div>
</template>

<script>
import Panle from '@/components/Panle.vue';
import PersButton from '@/components/PersButton.vue';
import SelectMaterial from '@/components/select-material';
import { listFiles, delFiles, batchRemove } from '@/api/files/files';
import { hasPermission } from '@/common/permission';
import { getToken } from '@/common/token';
import {uploadImage, uploadTemporaryFiles, updateUploadFiles, getList} from "@/api/scrm/files/files";
import parser from "postcss-selector-parser";

export default {
    components: {
        Panle,
        PersButton,
        SelectMaterial
    },
    data() {
        return {
            loading: false,
            IsShowMaterial: false,
            pageSize: 10, //一页显示多少条
            pageNumber: 1,
            total: 0, //总页数
            tableData: [],
            searchWord: '',
            searchType: '',
            formInline: {},


            checkKey: [],
            multipleSelection: [],

            actions: "/api/apiadmin/uploads/index",
            // actions: "http://localhost:8282/api/apiadmin/uploads/index",
            uploadHeader: {
                "Authorization": "Bearer " + getToken()
            },
            uploadData: {
                fileType: 0  // 0 图片，1 文件, 2 视频，3 其他
            },
            file_type: 'image',
        }
    },
    created() {
        this.init();
    },
    methods: {
        parser,
        hasPermission,
        init: function () {
            this.loading = true;
            let param = {
                "pageSize": this.pageSize,
                "pageNumber": this.pageNumber,
                "keyWord": this.searchWord,
                'type': this.searchType
            }
            getList(param).then((res) => {
                console.log(res);
                if (res.code == 200) {
                    this.tableData = res.data.list;
                    this.total = res.data.total;
                    this.loading = false;
                }
            })



        },
        getSearch: function () {
            this.searchWord = this.formInline.keyword;
            this.searchType = this.formInline.type;
            this.init();
        },
        handleSizeChange: function (e) {
            console.log(e);
            this.pageSize = e;
            this.init();
        },
        handleCurrentChange: function (e) {
            console.log(e);
            this.pageNumber = e;
            this.init();
        },
        handleSelectionChange: function (e) {
            console.log(e);
            let selectChang = []
            for (let item of e) {
                selectChang.push(item.fid)

            }
            this.multipleSelection = selectChang;
            console.log(selectChang);
        },





        delRole: function (data) {
            this.$confirm('确定删除【' + data.name + '】此文件', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                delFiles(data.fid).then((res) => {
                    if (res.code == 200) {
                        this.msgSuccess(res.msg);
                        this.init();
                    } else {
                        this.msgError(res.msg);
                    }
                })


            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },


        uploadSuccess: function (res) {
            console.log('上传cos成功', res);
            if (res.code == 200) {
                
                this.init();
                this.msgSuccess(res.msg);
            } else {
                this.msgError(res.msg);
            }
        },
        uploadError: function (res) {
            console.log(res);
            this.msgError(res.msg);
        },
        copy: function (data) {
            var oInput = document.createElement('input'); //创建一个隐藏input（重要！）
            oInput.value = data.http_urls; //赋值
            document.body.appendChild(oInput);
            oInput.select(); // 选择对象
            document.execCommand("Copy"); // 执行浏览器复制命令
            oInput.className = 'oInput';
            oInput.style.display = 'none';
            this.msgSuccess("复制成功")
        },
        delAll: function () {
            if (this.multipleSelection.length == 0) {
                this.$alert('请选择要删除的数据', '系统提示', {
                    confirmButtonText: '确定',
                    type: 'error',
                });
                return false;
            }
            this.$confirm('此操作将永久删除此数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let data = {
                    ids: this.multipleSelection
                }
                batchRemove(data).then((res) => {
                    if (res.code == 200) {
                        this.msgSuccess(res.msg);
                        this.init();
                    } else {
                        this.msgError(res.msg);
                    }
                })





            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
                this.$refs.multipleTable.clearSelection();
            });
        },
        syncAllFile: function () {
            this.loading = true;
            updateUploadFiles({
                page: 1
            }).then(res => {
                console.log('查询需要更新列表', res)
                if (res.code == 200) {
                    res.data.forEach(row => {
                        this.updateRole(row);
                    })
                } else {
                    this.msgError(res.msg);
                }
                this.loading = false;
            })
        },
        updateRole: function (row) {
            this.loading = true;
            // 更新
            updateUploadFiles({
                page: 2,
                id: row.id,
                type: row.type,
                oss_url: row.oss_url,
                expire_time: row.expire_time
            }).then(res => {
                console.log('更新完成', res)
                if (res.code == 200) {
                    this.msgSuccess(res.msg);
                    this.init();
                } else {
                    this.msgError(res.msg);
                }
                this.loading = false;
            })
        },
        showMaterial: function () {
            this.IsShowMaterial = true;
        },
        hideMaterial: function () {
            this.IsShowMaterial = false;
        },
        setTabType: function (tabId) {
            console.log('文件类型传：', tabId);
            // 上传文件类型变更，默认图片 image
            if (tabId > 0) {
                if (tabId == 1) {
                    this.file_type = 'file';
                } else if (tabId == 2) {
                    this.file_type = 'video';
                } else if (tabId == 3) {
                    this.file_type = 'voice';
                } else if (tabId == 4) {
                    this.file_type = 'file';
                }
            }
            console.log('文件类型：', this.file_type);
        },
        selectFile: function (data) {
            console.log('选择文件', data);
            data.forEach( item => {
                console.log(item.urls);
                // 上传素材库
                if (this.file_type === 'image') {
                    uploadImage({
                        media: item.urls,
                        name: item.name
                    }).then(res => {
                        console.log('图片上传企微成功', res);
                        this.msgSuccess(res.msg);
                        this.init();
                    });
                } else {
                    //上传素材库
                    uploadTemporaryFiles({
                        media: item.urls,
                        type: this.file_type,
                        name: item.name
                    }).then(res => {
                        console.log('上传企微成功', res);
                        this.msgSuccess(res.msg);
                        this.init();
                    });
                }
            })
            
        },
        
    }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/common";

.upload-demo {
    float: left;
    margin-right: 5px;
}

.demo-form-inline {
    .el-form-item {
        margin-bottom: 0;
    }
}

.el-tree {
    max-height: 200px;
    overflow: auto;
    background: #f7f7f7;
}

.el-tree-node__label,
.el-textarea__inner {
    font-size: 12px;
}

.groupmenu .el-tree-node__children .el-tree-node__children .el-tree-node__children .el-tree-node__content {
    float: left;
    width: 100px;
}

.el-checkbox__label {
    font-size: 12px !important;
}
</style>
